package cn.risebd.wechat.wechat.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.risebd.common.cache.RedisCache;
import cn.risebd.wechat.core.Wechat;
import cn.risebd.wechat.core.WechatBuilder;
import cn.risebd.wechat.model.base.AccessToken;
import cn.risebd.wechat.model.js.Ticket;
import cn.risebd.wechat.model.js.TicketType;

/**
 * @category 微信支持
 * @author Admin
 *
 */
@Service
public class WechatSupport {

	private static final Logger logger = LoggerFactory.getLogger(WechatSupport.class);

	@Autowired
	private RedisCache redisCache;

	private static final String ACCESSTOKEN = "ACCESSTOKEN:";

	private static final int ACCESSTOKENTIME = 2 * 60 * 60 - 60;

	private static final String JSAPITICKET = "JSAPITICKET:";

	private static final int JSAPITICKETTIME = 2 * 60 * 60 - 60;

	@Value("${appId}")
	private String appId;

	@Value("${appSecret}")
	private String appSecret;

	@Value("${token}")
	private String token;

	public String getAccessToken() {
		AccessToken accessToken = null;

		try {
			accessToken = redisCache.get(ACCESSTOKEN + appId);
		} catch (Exception e) {
			logger.error("缓存操作失败e={}", e);
		}
		if (null == accessToken) {
			Wechat wechat = WechatBuilder.newBuilder(appId, appSecret).build();
			accessToken = wechat.base().accessToken();
			try {
				redisCache.setex(ACCESSTOKEN + appId, ACCESSTOKENTIME, accessToken);
			} catch (Exception e) {
				logger.error("缓存操作失败e={}", e);
			}
		}
		return accessToken == null ? null : accessToken.getAccessToken();
	}

	public String getJSApiTicket() {
		Ticket ticket = null;
		/*
		 * try { ticket = redisCache.get(JSAPITICKET + appId + "-" +
		 * TicketType.JSAPI.name()); } catch (Exception e) {
		 * logger.error("缓存操作失败e={}", e); }
		 */
		if (null == ticket) {
			Wechat wechat = WechatBuilder.newBuilder(appId, appSecret).build();
			ticket = wechat.js().getTicket(TicketType.JSAPI);
			try {
				redisCache.setex(JSAPITICKET + appId + "-" + TicketType.JSAPI.name(), JSAPITICKETTIME, ticket);
			} catch (Exception e) {
				logger.error("缓存操作失败e={}", e);
			}
		}
		return ticket == null ? null : ticket.getTicket();
	}

	public String getToken() {
		return token;
	}

	public String getAppId() {
		return appId;
	}

	public String getAppSecret() {
		return appSecret;
	}

}
